package pers.cz.chat;

import io.netty.channel.Channel;
import pers.cz.chat.constants.JefClolorEnum;
import pers.cz.chat.utils.LogUtils;

import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @program: Jef-Chat
 * @description: 用户管理
 * @author: Cheng Zhi
 * @create: 2024-12-15 20:25
 **/
public class UserManager {

    public static Map<String, String> userMap = new ConcurrentHashMap<String, String>();

    private static final Map<String, Channel> onlineUsers = new ConcurrentHashMap<>();

    static {
        userMap.put("chengzhi", "123456");
        userMap.put("cz", "123");
        userMap.put("ktt", "123");
    }

    public static boolean userAuth(String userName, String passWord) {

        if (userName == null || userName.isEmpty()) {
            return false;
        }

        if (passWord == null || passWord.isEmpty()) {
            return false;
        }

        String pwd = userMap.get(userName);
	    return pwd != null && pwd.equals(passWord);
    }

    public static void registUser(String userName, String passWord) {
        userMap.put(userName, passWord);
    }
    public static void markOnline(String userName, Channel channel) {
        onlineUsers.put(userName, channel);
    }

    public static Channel getUserChannel(String userName) {
        return onlineUsers.get(userName);
    }

    public static void markOffline(Channel channel) {
        onlineUsers.entrySet().stream().filter(entry->entry.getValue().equals(channel)).forEach(entry->{
            LogUtils.print(JefClolorEnum.RED,"{}{}",entry.getKey() , "下线了！");
            onlineUsers.remove(entry.getKey());
        });
    }

    public static void markOffline(String userName) {
        onlineUsers.remove(userName);
    }

    public static Set<String> getOnlinUser() {
        return onlineUsers.keySet();
    }
}
